<template>
  <Dialog
    v-model="dialogVisible"
    :maxHeight="'800px'"
    width="80%"
    title="选择店铺"
    :before-close="() => closeDialog()"
  >
    <el-table :data="state.storeTableData" border style="width: 100%">
      <el-table-column width="55">
        <template #header>
          <el-checkbox v-model="state.checkAll" @change="handleCheckAllChange" />
        </template>
        <template #default="{ row }">
          <el-checkbox v-model="row.checked" @change="handleCheckChange" />
        </template>
      </el-table-column>

      <el-table-column :label="t('productMerge.storename')" prop="label">
        <template #default="{ row }">
          {{ row.label }}
        </template>
      </el-table-column>

      <el-table-column label="店铺链接" prop="buylink">
        <template #default="{ row }">
          <el-input v-model="row.buylink" :disabled="!row.checked" placeholder="请输入店铺链接" />
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <el-button class="m-r-4" @click="closeDialog"
        >{{ t('system.parameterConfig.cancel') }}
      </el-button>
      <el-button type="primary" @click="submit">{{ t('wholesalOrder.add') }}</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { getFieldEnumApi } from '@/api/productMerge'
import { Dialog } from '@/components/Dialog'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['exposeMultipleData'])
const { t } = useI18n()

const dialogVisible = ref<boolean>(false)

interface StoreTableItem {
  value: string | number
  label: string
  checked: boolean
  buylink: string
}

const state = reactive({
  storenameList: ref<Array<Record<string, any>>>([]),
  storeTableData: [] as StoreTableItem[],
  checkAll: false
})

// 全选/取消全选
const handleCheckAllChange = (val: boolean) => {
  state.storeTableData.forEach((item) => {
    item.checked = val
  })
}

// 单个选择变化
const handleCheckChange = () => {
  state.checkAll = state.storeTableData.every((item) => item.checked)
}

//点击添加按钮
const submit = () => {
  const selectedStorenames = state.storeTableData.filter((item) => item.checked)

  if (!selectedStorenames.length) return ElMessage.warning('请勾选店铺')

  // URL正则表达式
  const urlRegex = /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/

  // 验证店铺链接
  let buylinkResult = true
  for (const item of selectedStorenames) {
    // 先验证是否为空
    if (!item.buylink) {
      buylinkResult = false
      ElMessage.warning('请输入' + item.label + '店铺链接')
      break
    }

    // 验证URL格式
    if (!urlRegex.test(item.buylink)) {
      buylinkResult = false
      ElMessage.warning(item.label + '店铺链接格式不正确')
      break
    }
  }

  if (!buylinkResult) return

  emit('exposeMultipleData', selectedStorenames)
  closeDialog()
}

//点击取消关闭弹框
const closeDialog = () => {
  dialogVisible.value = false
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getFieldEnumApi({ field: 'all' })
  state.storeTableData = resp.data.storename
}

//初始化请求
const initialize = async (val: any[]) => {
  await getDropDownBoxInfo()
  console.log(val)
  if (!val?.length) return

  // 创建一个Set来优化查找
  const selectedValues = new Set(val.map((item) => item.value))

  // 直接更新状态
  state.storeTableData = state.storeTableData.map((item) => ({
    ...item,
    checked: selectedValues.has(item.value),
    buylink: val.find((v) => v.value === item.value)?.buylink
  }))
}

defineExpose({
  dialogVisible,
  initialize
})
</script>

<style lang="less" scoped>
:deep(.disabled-row) {
  color: #909399;
  cursor: not-allowed;
  background-color: #f5f7fa;

  .el-checkbox {
    cursor: not-allowed;
  }
}
</style>
